package com.manage.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.manage.controller.request.LoginRequest;
import com.manage.controller.request.RegRequest;
import com.manage.controller.request.UserUpdateRequest;
import com.manage.pojo.entity.User;
import com.manage.service.UserService;
import com.manage.util.ObjectUtil;
import com.manage.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.manage.controller.response.UserResponse;

import java.util.List;


@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    @PostMapping("/login")
    public Result login(@RequestBody LoginRequest request){
        User user = userService.login(request);
        if (user == null) {
            return Result.error("账号或密码错误");
        }
        return Result.success("登陆成功", ObjectUtil.clone(user, UserResponse.class));
    }

    @PostMapping("/update")
    public Result updateUser(@RequestBody UserUpdateRequest request) {
        User user = ObjectUtil.clone(request, User.class);
        userService.updateById(user);
        return Result.success("修改成功");
    }

    @GetMapping("/list/{role}")
    public List<UserResponse> listUserByRole(@PathVariable("role") Integer role) {
        List<User> user = userService.list(new QueryWrapper<User>().eq("role", role));
        return  ObjectUtil.cloneList(user, UserResponse.class);
    }

    @PostMapping("/reg")
    public Result reg(@RequestBody RegRequest request) {
        User user = userService.getOne(new QueryWrapper<User>().eq("username", request.getUsername()));
        if(user != null) {
            return Result.error("用户名已存在！");
        }

        User clone = ObjectUtil.clone(request, User.class);
        userService.save(clone);
        return Result.success("注册成功", clone);
    }
}
